<?php


namespace App\Http\Requests\Customer\Warehouse\Receiving;


use App\Models\Customer;
use App\Models\Product;
use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    /**
     * @return array
     * @author: luffyzhao@vip.126.com
     * @datetime: 2019/3/28 16:00
     */
    public function rules(): array
    {
        return [
            'products' => ['required', 'array'],
            'products.*.sku' => ['required', 'string', function ($attribute, $value, $fail) {
                /** @var Customer $customer */
                $customer = app('customer');
                /** @var Product $product */
                $product = Product::query()
                    ->where('customer_id', '=', $customer->getKey())
                    ->where('sku', '=', $value)->first(['id', 'sku', 'status']);
                if (!$product->isNormal()) {
                    return $fail(sprintf("产品[%s]不是正常状态，不能入库！", $product->getAttribute('sku')));
                }
            }],
            'products.*.lot' => ['nullable', 'string'],
            'products.*.price' => ['required', 'numeric'],
            'products.*.quantity' => ['required', 'integer', 'min:1'],
            'district' => ['required', 'size:4'],
            'type' => ['required', 'size:1', 'in:0,1,2'],
            'transport' => ['required', 'size:1'],
            'packing' => ['required', 'size:1'],
            'weight' => ['required', 'numeric', function ($attribute, $value, $fail) {
                $weight = collect($this->input('products'))->sum(function ($item) {
                    /** @var Customer $customer */
                    $customer = app('customer');
                    $weight = Product::query()
                        ->where('customer_id', '=', $customer->getKey())
                        ->where('sku', '=', $item['sku'])->value('weight');
                    return bcmul($item['quantity'], $weight, 3);
                });
                if ($weight > $value) {
                    return $fail("产品毛重不能大于货物毛重！");
                }
            }],
            'piece' => ['required', 'numeric'],
            'remark' => ['nullable'],
            'files' => ['required', 'array'],
            'files.*' => ['required', 'array'],
            'files.*.type' => ['required', 'string'],
            'files.*.url' => ['required', 'string'],
        ];
    }
}